import { IAppDataEntity, IAppDEDataImport } from '@ibiz/model-core';
import { useNamespace } from '@ibiz-template/vue3-util';
import { defineComponent, ref, PropType } from 'vue';

import './data-import.scss';
import {
  asyncImportData,
  importData,
  ImportDataResult,
} from '@ibiz-template/runtime';

export const DataImport = defineComponent({
  name: 'DataImport',
  props: {
    dismiss: {
      type: Function as PropType<() => void>,
      required: true,
    },
    appDataEntity: {
      type: Object as PropType<IAppDataEntity>,
      required: true,
    },
    dataImport: {
      type: Object as PropType<IAppDEDataImport>,
      required: false,
    },
  },
  setup(props) {
    const ns = useNamespace('data-import');
    const inputUpLoad = ref();
    const message = ref<{
      state: 'ready' | 'over' | 'error';
      message: string;
    }>({
      state: 'ready',
      message: '',
    });

    const errorMessage = ref('');

    const isLoading = ref(false);

    const onCancelButtonClick = () => {
      props.dismiss();
    };

    // 文件选择变更事件
    const onFileChange = async ($event: Event) => {
      const obj = $event.target as IData;
      if (!obj.files) {
        return;
      }
      errorMessage.value = '';
      const selectedFile = obj.files[0];
      obj.value = null; // 置空不然下次文件不变不触发
      let result: ImportDataResult;
      isLoading.value = true;
      try {
        if (ibiz.env.enableMqtt) {
          asyncImportData(selectedFile, props.appDataEntity, props.dataImport);
          ibiz.notification.info({
            desc: ibiz.i18n.t('component.dataImport.startImport'),
          });
          onCancelButtonClick();
          return;
        }
        result = await importData(
          selectedFile,
          props.appDataEntity,
          props.dataImport,
        );

        // 模拟表单通知 刷新表格
        ibiz.mc.command.send(
          { srfdecodename: props.appDataEntity.codeName },
          'OBJECTCREATED',
        );
        const { success, total, message: _message } = result;
        const totalNum = total ? Number(total) : 0;
        const successNum = success ? Number(success) : 0;
        const errorNum = total - success;
        message.value.state = _message ? 'error' : 'over';
        message.value.message =
          _message ||
          ibiz.i18n.t('component.dataImport.importSuccess', {
            totalNum,
            successNum,
            errorNum,
          });
      } catch (error) {
        if (error instanceof Error) {
          errorMessage.value = error.message as string;
        }
      } finally {
        isLoading.value = false;
      }
    };

    // 下载模板文件
    const onLinkClick = async () => {
      let templateUrl = `${props.appDataEntity.codeName2!.toLowerCase()}/importtemplate`;
      if (props.dataImport?.codeName) {
        templateUrl += `?srfimporttag=${props.dataImport.codeName}`;
      }
      const res = await ibiz.net.request(templateUrl, {
        responseType: 'blob',
      });
      if (res.status === 200) {
        let fileName =
          res.headers['content-disposition']!.split(';')
            .find((str: string) => str.indexOf('filename=') !== -1)
            ?.slice(9) || '';
        fileName = decodeURIComponent(fileName);
        const blob = new Blob([res.data as Blob], {
          type: 'application/vnd.ms-excel',
        });
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      }
    };

    const selectFile = () => {
      inputUpLoad.value.click();
    };

    return {
      ns,
      onLinkClick,
      selectFile,
      onCancelButtonClick,
      onFileChange,
      inputUpLoad,
      isLoading,
      message,
      errorMessage,
    };
  },
  render() {
    return (
      <div class={this.ns.b()} v-loading={this.isLoading}>
        <input
          ref='inputUpLoad'
          type='file'
          style='display: none'
          accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          onChange={this.onFileChange}
        />
        <div class={this.ns.e('caption')}>
          {ibiz.i18n.t('component.dataImport.importData')}
        </div>
        {this.message.state === 'ready' ? (
          <div class={this.ns.b('upload')} onClick={this.selectFile}>
            <img
              class={this.ns.be('upload', 'img')}
              src='./assets/images/icon-import.svg'
            ></img>
            <span class={this.ns.be('upload', 'text')}>
              {ibiz.i18n.t('component.dataImport.clickToUpload')}
            </span>
          </div>
        ) : (
          <div class={[this.ns.b('message')]}>
            <div class={this.ns.be('message', 'title')}>
              {ibiz.i18n.t('component.dataImport.importResults')}
            </div>
            <div
              class={[
                this.ns.be('message', 'content'),
                this.ns.is('error', this.message.state === 'error'),
              ]}
            >
              {this.message.message}
            </div>
          </div>
        )}
        {this.errorMessage && (
          <div class={this.ns.b('error-message')}>{this.errorMessage}</div>
        )}
        <div class={this.ns.e('template-container')}>
          <div class={this.ns.e('template-description')}>
            {ibiz.i18n.t('component.dataImport.downloadTemplate')}
          </div>
          <div class={this.ns.e('template-link')} onClick={this.onLinkClick}>
            <ion-icon class={this.ns.e('link-icon')} name='link' />
            {this.appDataEntity.logicName}
            {ibiz.i18n.t('component.dataImport.templateFile')}
          </div>
        </div>
        <div class={this.ns.e('button-bar')}>
          <el-button onClick={this.onCancelButtonClick}>
            {ibiz.i18n.t('app.cancel')}
          </el-button>
          {this.message.state !== 'ready' && (
            <el-button onClick={this.selectFile}>
              {ibiz.i18n.t('component.dataImport.continue')}
            </el-button>
          )}
        </div>
      </div>
    );
  },
});
